﻿$(document).ready(function () {

    function apiRequest(params) {
        var verb = params.verb || 'GET';
        var method = params.method || 'Items';
        var data = params.data || {};

        // Fix the command argument for the indata
        if (method == 'Items') {
            data = { command: JSON.stringify(data) };
        }

        var processdata = params.processData || true;
        var datatype = params.datatype || "json";
        var cache = params.cache || false;
        var async;
        (params.async === false) ? async = false : async = true;

        //Start spinner
        //var s = $('#mpspinner');
        //var spinner = false;

        //if (s.length > 0) spinner = true;

        //if (spinner) s.show();

        $.ajax({
            dataType: datatype,
            type: verb,
            contentType: "application/json",
            data: data,
            async: async,
            cache: cache,
            processData: processdata,
            url: '/_vti_bin/Camelot.JSONAPI/jsonapi.svc/' + method,
            error: function (xhr, textStatus, errorThrown) {
                params.error(xhr, textStatus, errorThrown);

                //if (spinner) s.hide();
            },
            success: function (data, textStatus, xhr) {
                params.success(data, textStatus, xhr);

                //if (spinner) s.hide();
            }
        });
    }

    // Expose
    var core = {
        apiRequest: apiRequest
    };

    $.camelot = core;

});


String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); };

String.prototype.ltrim = function () { return this.replace(/^\s+/, ''); };

String.prototype.rtrim = function () { return this.replace(/\s+$/, ''); };

String.prototype.fulltrim = function () { return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' '); };

Array.prototype.clean = function (deleteValue) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == deleteValue) {
            this.splice(i, 1);
            i--;
        }
    }
    return this;
};

String.prototype.TruncateAtWord = function (wordCount) {
    var text = this;
    text = text.replace(/<(?:.|\n)*?>/gm, '');
    var textArray = text.split(' ');

    if (wordCount >= textArray.length) {
        return text;
    }
    
    textArray.splice(wordCount - textArray.length, textArray.length);
    return textArray.join(' ') + '...';
};
